#!/usr/bin/env python
# -*- coding: utf-8 -*- #   
#
# Copyright 2007 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#

from google.appengine.ext import db
import cgi
from google.appengine.api import users
import Cookie,urllib
from django.utils import simplejson
from google.appengine.api import urlfetch

from google.appengine.ext import webapp
from google.appengine.ext.webapp import util
from google.appengine.ext.webapp.util import run_wsgi_app
import time
from google.appengine.ext import db
SiteName=u"西工大附中北大清华同学会"
SiteLogo=u'"/image/logo.jpg"'
SchoolName=u"西工大附中"
superadminname="wsmlby@gmail.com"
renren_usr ='414197593@qq.com'

renren_passwd ='wenjian'

#'3y2212'#'xgzfd0@gmail.com'
import re
cookie_buf = Cookie.SimpleCookie()
def make_cookie_header(cookie):
	ret = ''
	for v in cookie.values():
		ret += '%s=%s;' % (v.key, v.value)
	return ret
 
def login2renren():
	verify_url = 'http://passport.renren.com/PLogin.do'
	verify_data= urllib.urlencode({
		'domain':'renren.com',
		'email':  renren_usr,
		'password': renren_passwd,
		'origURL':'http://home.renren.com/Home.do',
	})
	result = urlfetch.fetch(
		url=verify_url,
		headers={
			'Cookie':make_cookie_header(cookie_buf),
			'Content-Type': 'application/x-www-form-urlencoded',
			'user-agent':'Mozilla/5.0 (Linux; U; Linux i686; en-US) Gecko/20100115 Firefox/3.6',
		},
		method=urlfetch.POST,
		payload=verify_data,
		follow_redirects = False,
	)
	return result
 

def do_redirect(url, cookie):
	result = urlfetch.fetch(
		url=url,
		headers={
			'Cookie':make_cookie_header(cookie),
			'Content-Type': 'application/x-www-form-urlencoded',
			'user-agent':'Mozilla/5.0 (Linux; U; Linux i686; en-US) Gecko/20100115 Firefox/3.6',
		},
		method=urlfetch.GET,
		follow_redirects = False,
	)
	return result
 
def send_status(status, cookie):
	status_url = 'http://status.renren.com/getdoing.do'
	result = urlfetch.fetch(
		url=status_url,
		headers={
			'Cookie':make_cookie_header(cookie),
			'Content-Type': 'application/x-www-form-urlencoded',
			'user-agent':'Mozilla/5.0 (Linux; U; Linux i686; en-US) Gecko/20100115 Firefox/3.6',
		},
		method=urlfetch.GET,
	)
	cookie_buf = Cookie.SimpleCookie(result.headers.get('set-cookie', ''))
	ticket = re.search('<input type="hidden" value="(-?\d+)" class="submit" id="publisher_form_ticket"/>', result.content)
	status_url = 'http://status.renren.com/doing/update.do'
	status_data = urllib.urlencode({'c': status.encode('utf-8'),'raw': status.encode('utf-8'),'isAtHome': 0,'publisher_form_ticket': ticket.group(1)})
	result = urlfetch.fetch(url=status_url,headers={'Cookie':make_cookie_header(cookie),'Content-Type': 'application/x-www-form-urlencoded','user-agent':'Mozilla/5.0 (Linux; U; Linux i686; en-US) Gecko/20100115 Firefox/3.6','Referer': 'http://status.renren.com/getdoing.do'},method=urlfetch.POST,payload=status_data,)
	return True
	
def send_to_renren(str):
	result=login2renren()
	cookie_buf = Cookie.SimpleCookie(result.headers.get('set-cookie', ''))
	callback_url = result.headers.get('location','xx')
	result = do_redirect(callback_url, cookie_buf)
	cookie_buf = Cookie.SimpleCookie(result.headers.get('set-cookie', ''))
	send_status(str, cookie_buf)
def isadmin(usr):
	admins=Member.gql("WHERE username = :1 ",
                                 usr)
	for admin in admins:
		return admin.isadmin
def ismember(usr):
	members=db.GqlQuery("SELECT * FROM Member WHERE username=:user ",user=usr)
	for member in members:
		if member.waitforcer==False:
			return True
	return False
def iscer(usr):
	members=db.GqlQuery("SELECT *  FROM Member WHERE username=:user ",user=usr)
	for member in members:
		if member.waitforcer:
			return 1
		else:
			return 2
	return 0
def getkey(url,pattern,end=""):
	x=len(pattern)
	a=url.find(pattern)
	if end!="":
		b=url.find(end)
	else:
		b=url.find('?admin')
	if b!=-1:
		return url[a+x:b]
	else:
		return url[a+x:]
			
def Admined(slf):
	if slf.request.url.find('?admin')!=-1:
		return True
	else:
		return False
def Header(slf,str=SiteName):
	slf.response.out.write(u"""<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />""")
	slf.response.out.write(u"<title>%s</title>"%str)
	slf.response.out.write(u"""
<link href="/style.css" rel="stylesheet" type="text/css" />
<style type="text/css">
<!--
.style1 {color: #A1DBFF}
-->
</style>
</head>

<body>
<div id="wrap">
<div id="menu">
<!--Menu start-->
  <div id="tabsJ">
  <ul>
    <li><a href="/"><span>首页</span></a></li>
    <li><a href="/forum"><span>论坛</span></a></li>
    <li><a href="/database"><span>数据库</span></a></li>

		""")
	user=users.get_current_user()
	if user:
		outurl=users.create_logout_url(slf.request.uri)
		if isadmin(user):
			if not Admined(slf):
				slf.response.out.write(u"""<li><a href="%s?admin" title="管"><span>管理员页面</span></a></li>"""%slf.request.uri)
			else:
				slf.response.out.write(u"""<li><a href="%s" ><span>普通页面</span></a></li>"""%slf.request.uri[0:slf.request.url.find('?admin')])
		if ismember(user):
			slf.response.out.write(u"""<li><a href="" ><span>已是会员</span></a></li>""")
		else:
			slf.response.out.write(u"""<li><a href="/cer" ><span>会员认证</span></a></li>""")
		
		slf.response.out.write(u"""<li><a href="%s" ><span>Logout</span></a></li> </ul></div>"""%outurl)
		slf.response.out.write(u"""<div align="right"><a href="/profile">%s</a></div>"""%user.email())
			
	else:
		inurl=users.create_login_url(slf.request.uri)
		slf.response.out.write(u"""<li><a href="%s" ><span>Login</span></a></li> </ul></div>"""%inurl)
	slf.response.out.write("""   
 

</div>
<!--Menu end-->


<!--Header start-->
<div id="header">
  <div class="title">%s</div>
</div>
<!--Header end-->"""%str)
	return user
def Ender(slf,str=SiteName):
	slf.response.out.write(u"""
<!--Footer start-->
<div id="footer"><br /><a href="/">首页</a> <a href="/forum">论坛</a> <a href="/database">数据库</a></div>
<!--Footer end-->
<div id="bottom_line"></div>
</div>

</body>
</html>""")
MaxLevel=2	
class Member(db.Model): #members
	username=db.UserProperty()
	emails=db.StringListProperty()
	name_chs=db.StringProperty("")
	name_eng=db.StringProperty("")
	sex=db.BooleanProperty()#0 for female ,1 for male
	class_in_school=db.StringProperty()
	year_of_grad=db.IntegerProperty()
	phone=db.PhoneNumberProperty()
	#school=db.StringProperty()
	postal=db.PostalAddressProperty()
	universities=db.StringListProperty()#universities you have been
	major=db.StringListProperty()
	birthday=db.DateProperty()
	locations=db.StringListProperty()#where you have been ,loc[0]=where you are now
	msn=db.StringProperty()
	qq=db.StringProperty()
	worked=db.StringListProperty()
	position=db.StringListProperty()#what you do in worked[i]
	isadmin=db.BooleanProperty()
	waitforcer=db.BooleanProperty()
class Block(db.Model): # the tree of blocks
	level=db.IntegerProperty()
	belongto=db.StringProperty()
	name=db.StringProperty()
	introduction=db.StringProperty()
	num_art=db.IntegerProperty()
class Article(db.Model):
	author=db.UserProperty()
	title=db.StringProperty()
	content=db.TextProperty()
	date=db.DateTimeProperty(auto_now_add=True)
	belongto=db.StringProperty("")
	num_reply=db.IntegerProperty(0)
class Reply(db.Model):
	author = db.UserProperty()
	ip=db.StringProperty()
	content = db.StringProperty(multiline=True)
	date = db.DateTimeProperty(auto_now_add=True)
	tokey=db.StringProperty()
class News(db.Model): #the list of news on the homepage
	NewsTitle=db.StringProperty()
	NewsURL=db.StringProperty()
	date=db.DateTimeProperty(auto_now_add=True)
	
class Log(db.Model): #the logs
	user=db.UserProperty()
	ip=db.StringProperty()
	date = db.DateTimeProperty(auto_now_add=True)



